package com.sky.aop;


import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Before("@annotation(com.sky.aop.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {

        Signature signature = joinPoint.getSignature();
        log.info("[自动填充切面] method:{}", signature.getName());


        MethodSignature methodSignature = (MethodSignature) signature;

        Method method = methodSignature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);


        try {
            // 获取到方法实体类

            Object[] args = joinPoint.getArgs();
            Object entry = args[0];

            if (annotation.value() == OperationType.INSERT) {
                log.info("[自动填充-插入] entry:{}", entry);
                // 获取到方法
                Method setCreateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                // 为参数赋值
                setCreateTime.invoke(entry, LocalDateTime.now());
                setUpdateTime.invoke(entry, LocalDateTime.now());
                setCreateUser.invoke(entry, BaseContext.getCurrentId());
                setUpdateUser.invoke(entry, BaseContext.getCurrentId());

                log.info("【自动填充-新增】填充后：entry{}",entry);

            } else {
                log.info("[自动填充-更新] entry:{}",entry);

                // 获取到方法
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                // 为参数赋值
                setUpdateTime.invoke(entry, LocalDateTime.now());
                setUpdateUser.invoke(entry, BaseContext.getCurrentId());

                log.info("【自动填充-更新】填充后：entry{}",entry);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
